package beavers.studio.golfberry.screens;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.LabelField;

import org.json.me.JSONArray;
import org.json.me.JSONException;

import beavers.studio.golfberry.FileManager;
import beavers.studio.utilities.Utils;
import beavers.studio.utilities.callbacks.WebDataCallback;
import beavers.studio.utilities.threads.PictureDownloadThread;

public class PictureScreen extends GolfScreen implements WebDataCallback {
	//Flag for download
	private boolean m_Download = false;
	
	//Static attribute
	public static boolean m_Run	= false;
	
	public PictureScreen() {
		//Super
		super(GolfScreen.ID.PIC);

		//Check best pictures, change this so according to competition
		Utils.getWebData("http://localhost/golfberry/index.php/snapshot/get_all_photos/1", this);
	}

	public void callback(byte[] JSON) {		
		add(new LabelField(new String(JSON)));
		
		//Enter callback
		try {
			//Parse JSON
			JSONArray json = new JSONArray(new String(JSON));
			
			//Check length
			int length = json.length()>5 ? 5 : json.length();
			
			//Put into array
			String[] urls = new String[length];
			for (int i=0;i<length;i++) {
				urls[i] = json.getString(i);
			}
			
			//Display available pictures
			byte[] m_Image;
			for (int i=0;i<length;i++) {
				//Parse
				int index = urls[i].lastIndexOf('/');
				String url = (index!=-1) ? urls[i].substring(index) : urls[i];
				
				//Check picture
				if ((m_Image=FileManager.inst().loadImage(url))!=null) {
					//Add to screen
					add(new BitmapField(Bitmap.createBitmapFromBytes(m_Image, 0, m_Image.length, 1)));
					
					//Reset pointer
					urls[i]=null;
				} else {
					//Set flag to download
					m_Download = true;
				}
			}
			
			//Download
			if (!m_Run&&m_Download) {
				PictureDownloadThread m_Thread = new PictureDownloadThread(this, urls);
				m_Thread.start();
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}
